//
//  NetworkManager.swift
//  VVbo
//
//  Created by Mr.Run on 2017/8/23.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod {
    case GET
    case POST
}

class NetworkManager: AFHTTPSessionManager {
    
    static let shared = { ()->NetworkManager in
        let instance = NetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }
//    var accessToken:String? //= "2.00piw1VCLlbpYB34c0a5945d0AxCSb"
//    var uid: String? = "2295324371"
    
    lazy var userAccount = UserAcconut()
    
    var userLogon: Bool {
        return userAccount.access_token != nil
    }
    
    
    func tokenRequest(method: HTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion:@escaping (_ json:Any?, _ isSuccess: Bool)->()) {
        
        guard let token = userAccount.access_token else {
//            print("没有token, 需要登录")
            //  发送登录通知
            completion(nil, false)
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: nil)
            
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            parameters = [String: Any]()
        }
        parameters!["access_token"] = token
//        request(URLString: URLString, parameters: parameters!, completion: completion)
        request(method: method, URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    func request(method: HTTPMethod = .GET, URLString: String, parameters: [String: Any], completion:@escaping (_ json:Any?, _ isSuccess: Bool)->()) {
        let success = { (task:URLSessionDataTask, json: Any?)->() in
            completion(json, true)
        }
        
        let fail = { (task:URLSessionDataTask?, error: NSError)->() in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                // 发送登录通知
//                print("token过期")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: "bad token")
                
            }
            
            print(error)
            completion(nil, false)
        }
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: fail as? (URLSessionDataTask?, Error) -> Void)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: fail as? (URLSessionDataTask?, Error) -> Void)
        }
    }
}
